﻿/**
 * 并排条形图
 */
define(function (require, exports, module) {
    var modules = {
        colorHelper: require('../../util/colorHelper'),
        ObjectHelper: require('../../util/objecthepler')
    }
    var buildChart = function (svgSelector, data, columnFields, rowFields, options) {
        //一级维度
        var dimensionField = columnFields.find(function (d) { return d.slaveType === 0; });
        //度量
        var measureField = rowFields.find(function (d) { return d.slaveType === 1; });
        //条形图呈现方向判定
        var direction = "vertical";
        if (!dimensionField) {
            direction = "horizon";
            dimensionField = rowFields.find(function (d) { return d.slaveType === 0; });
            measureField = columnFields.find(function (d) { return d.slaveType === 1; });
        }
        if (!dimensionField || !measureField || !options.colorMark) {
            return false;
        }
        //二级维度
        var subdimensionField = options.colorMark.annexField;
        var config = options.chartConfig;
        if (!config) {
            config = {
                GlobalColor: "#4E79A7",
                MultiColors: ["#4E79A7", "#A0CBE8", "#F28E2B", "#FFBE7D", "#59A14F", "#8CD17D", "#B6992D", "#F1CE63", "#499894", "#86BCB6", "#E15759", "#FF9D9A", "#79706E", "#BAB0AC", "#D37295", "#FABFD2", "#B07AA1", "#D4A6C8", "#9D7660", "#D7B5A6"],
                scale: 0.8,
                axisStyle: {
                    tickColor: "#000",
                    fontColor: "#000",
                    fontFamily: "Arial",
                    fontSize: 12
                },
                textStyle: {
                    "display": "none",
                    "font-family": "Arial",
                    "font-size": 12,
                    "font-style": "normal",
                    "font-weight": "normal",
                    "fill": "#333",
                    "position": "top"
                }
            }
        }
        //提取一级维度
        var categories = Enumerable.from(data).select(function (d) { return d[dimensionField.name]; }).distinct().orderBy().toArray();
        //按二级维度分组
        var groups = Enumerable.from(data).groupBy(function (d) { return d[subdimensionField.name]; }).toArray();
        //轴文字样式
        var axis_nameTextStyle = {
            color: config.axisStyle.fontColor,
            fontSize: config.axisStyle.fontSize,
            fontFamily: config.axisStyle.fontFamily
        }
        var option_chart = {
            color: config.MultiColors,
            legend: {
                data: [],
                textStyle: axis_nameTextStyle
            },
            toolbox: {
                show: true,
                //orient: 'vertical',
                //top: 'center',
                right: 10,
                feature: {
                    mark: { show: true },
                    dataView: { show: true, readOnly: false },
                    saveAsImage: { show: true }
                },
                iconStyle: {
                    borderColor: config.axisStyle.fontColor,
                    textPosition: "left"
                }
            },
            calculable: true,
            series: [],
            others: {
                dimensionField: dimensionField,
                measureField: measureField,
                subdimensionField: subdimensionField,
                categories: categories
            }
        }
        //数据条标签配置
        var labelOption = {
            normal: {
                show: config.textStyle["display"] !== "none",
                distance: 5,
                align: "left",
                verticalAlign: "middle",
                fontSize: config.textStyle["font-size"],
                fontFamily: config.textStyle["font-family"],
                color: config.textStyle["fill"]
            }
        };

        //轴线配置
        var axis_axisLine = {
            lineStyle: {
                color: config.axisStyle.tickColor
            }
        }
        if (direction === "vertical") {
            labelOption.normal.rotate = 90;
            labelOption.normal.position = "insideBottom";
            option_chart.xAxis = [{
                type: 'category',
                axisTick: { show: false },
                data: categories,
                name: dimensionField.name,
                nameTextStyle: axis_nameTextStyle,
                axisLine: axis_axisLine,
                axisLabel: axis_nameTextStyle,
                nameLocation: "middle",
                nameGap:config.axisStyle.fontSize*1.8
            }];
            option_chart.yAxis = [{
                type: 'value',
                name: measureField.name,
                nameTextStyle: axis_nameTextStyle,
                axisLine: axis_axisLine,
                axisTick: axis_axisLine,
                axisLabel: axis_nameTextStyle
            }];
        } else {
            labelOption.normal.rotate = 0;
            labelOption.normal.position = "insideLeft";
            option_chart.xAxis = [{
                type: 'value',
                name: measureField.name,
                nameTextStyle: axis_nameTextStyle,
                axisLine: axis_axisLine,
                axisTick: axis_axisLine,
                axisLabel: axis_nameTextStyle,
                nameLocation: "middle",
                nameGap:config.axisStyle.fontSize*1.8
            }];
            option_chart.yAxis = [{
                type: 'category',
                axisTick: { show: false },
                data: categories,
                name: dimensionField.name,
                nameTextStyle: axis_nameTextStyle,
                axisLine: axis_axisLine,
                axisLabel: axis_nameTextStyle,
                nameLocation: "start",
                inverse:true
            }];
        }
        groups.forEach(function (group) {
            var legend = group.key();
            option_chart.legend.data.push(legend);
            var source = group.getSource();
            var serie = {
                name: legend,
                type: 'bar',
                label: labelOption,
                data: []
            }
            option_chart.series.push(serie);
            categories.forEach(function (c) {
                var find = source.find(function (d) { return d[dimensionField.name] === c; });
                if (find) {
                    serie.data.push(find[measureField.name]);
                } else {
                    serie.data.push(0);
                }
            });
        });
        var dom_container = $(svgSelector).children('#chart')[0];
        var chartInstance = new chart(dom_container, option_chart);
        return chartInstance;
    }
    var chart = function (dom_container, opt) {
        var self = this;
        var myChart = echarts.init(dom_container);
        var chart_opt = {
            brush: {
                toolbox: ['rect', 'clear'],
                throttleType: "debounce",
                throttleDelay: 500
            },
            tooltip: {
                trigger: 'item',
                axisPointer: {
                    type: 'shadow'
                },
                formatter: function (args) {
                    return opt.others.dimensionField.name + ":" + args.name + "<br/>" + opt.others.subdimensionField.name + ":" + args.seriesName + "<br/>" + opt.others.measureField.name + ":" + Number(args.value).toMeasureFormart(opt.others.measureField.numberFormat);
                }
            }
        }
        var labelFormatter = function (args) {
            return args.seriesName + " " + args.value.toMeasureFormart(chart_opt.others.measureField.numberFormat);
        }
        var setOption = function (opt) {
            chart_opt = $.extend(chart_opt, opt);
            chart_opt.series.forEach(function (d) {
                d.label.normal.formatter = labelFormatter;
            });
            myChart.setOption(chart_opt);
        }
        //响应点击事件
        myChart.on("click", function (args) {
            if (args.componentType === "series") {
                var calldata = [{
                    field: chart_opt.others.dimensionField,
                    value: [args.name]
                }, {
                    field: chart_opt.others.subdimensionField,
                    value: [args.seriesName]
                }];
                if (self.onselected) {
                    self.onselected(calldata);
                }
            }
        });
        //响应框选事件
        myChart.on('brushSelected', function (args) {
            if (args.batch.length) {
                var selectedSeries = args.batch[0].selected.filter(function (d) { return d.dataIndex.length; });
                var c_idx = Array.prototype.concat.apply([], selectedSeries.map(function (d) { return d.dataIndex; }));
                c_idx = Enumerable.from(c_idx).distinct().toArray();
                var categories = [];
                chart_opt.others.categories.forEach(function (d, idx) {
                    if (c_idx.includes(idx)) {
                        categories.push(d);
                    }
                });
                var calldata = [{
                    field: chart_opt.others.dimensionField,
                    value: categories
                }, {
                    field: chart_opt.others.subdimensionField,
                    value: selectedSeries.map(function (d) { return d.seriesName; })
                }];
                if (self.onselected) {
                    self.onselected(calldata);
                }
            }
        });
        if (opt) {
            setOption(opt);
        }
        this.setOption = setOption;
        this.removeChart = function () {
            myChart.dispose();
        }

    }
    module.exports = {
        build: buildChart
    }
});
